/*
* Description: jqGrid extention for overriding the method of columnChooser
* Dependency: jQuery/jQuery UI/jqGrid 
* Copyright (c) HP
* Date: 2012-10-25
* Author: ShenXiaoWei
*/

;(function($){
      
$.jgrid.extend({
	occColumnChooser:function(opts , searchTableId , mutiselectPopCoverCobject , initInnerHtml){
		var self = this;
		if($("#colchooser_"+$.jgrid.jqID(self[0].p.id)).length ) { return; }
	    var selector = $('<div id="colchooser_'+self[0].p.id+'" style="position:relative;overflow:hidden"><div><select multiple="multiple"></select></div></div>');
	  //  var selector = $('<div id="colchooser_conditionSel" style="position:relative;overflow:hidden"><div><select multiple="multiple"></select></div></div>');
	    var select = $('select', selector);
		
		function insert(perm,i,v) {
			if(i>=0){
				var a = perm.slice();
				var b = a.splice(i,Math.max(perm.length-i,i));
				if(i>perm.length) { i = perm.length; }
				a[i] = v;
				return a.concat(b);
			}
		}
	    opts = $.extend({
	        "width" : 760,
	        "height" : 240,
	        "classname" : null,
	        "done" : function(perm) { if (perm) { self.jqGrid("remapColumns", perm, true); } },
	        /* msel is either the name of a ui widget class that
	           extends a multiselect, or a function that supports
	           creating a multiselect object (with no argument,
	           or when passed an object), and destroying it (when
	           passed the string "destroy"). */
	        "msel" : "multiselect",
	        /* "msel_opts" : {}, */
	
	        /* dlog is either the name of a ui widget class that 
	           behaves in a dialog-like way, or a function, that
	           supports creating a dialog (when passed dlog_opts)
	           or destroying a dialog (when passed the string
	           "destroy")
	           */
	        "dlog" : "dialog",
			"dialog_opts" : {
				"minWidth": 470
			},
			/**
			 * custom funciton : save display columns
			 */
			"showColDym":function(){
				var columnCode = "",columnName = "",columnType = "",columnSize = "",columnUrl = "";
				var gridId = $("#gridHiddenId").val();
				
				 $('option',select).each(function() {
	                    if (this.selected) {
	                        //self.jqGrid("showCol", colModel[this.value].name);
	                    	columnName+=colNames[this.value]+",";
	                    	columnCode+=colModel[this.value].name+",";
	                    	columnType+=colModel[this.value].model+",";
	                    	columnSize+=colModel[this.value].index+",";
	                    	columnUrl+=colModel[this.value].url+",";
	                    }
	                }); 
				// save show columns
					$.ajax({
						type:"POST",
						//dataType: "json",
						url:"/orm/saveCustomizeConditions.action",
						data: {
							functionName: $("#centerBaseOutFunctionName").val(),
							tableName:$("#centerBaseOutTableName").val(),
							columnName: columnName,
							columnCode: columnCode,
							columnType: columnType,
							columnSize: columnSize,
							columnUrl:columnUrl
						}
					});				 
			},
	        /* dlog_opts is either an option object to be passed 
	           to "dlog", or (more likely) a function that creates
	           the options object.
	           The default produces a suitable options object for
	           ui.dialog */
	        "dlog_opts" : function(opts) {            	
	        	var self = this;
	
	            var buttons = {};
				buttons['保存自定义条件'] = function() {
					opts.showColDym();
					opts.apply_perm();
	                opts.cleanup(false);                    
	            };
	        	            	
	           
	            buttons[opts.bSubmit] = function() {
	                opts.apply_perm();
	                opts.cleanup(false);
	            };
	            buttons[opts.bCancel] = function() {
	                opts.cleanup(true);
	            };
	            return $.extend(true, {
	                "buttons": buttons,
	                "close": function() {
	                    opts.cleanup(true);
	                },
					"modal" : opts.modal ? opts.modal : false,
					"resizable": opts.resizable ? opts.resizable : true,
	                "width": opts.width+20
	            }, opts.dialog_opts || {});
	        },
	        /* Function to get the permutation array, and pass it to the
	           "done" function */
	        "apply_perm" : function() {
	        	var columnCode = new Array;
	        	var columnName = new Array;
	        	var columnType = new Array;
	        	var columnUrl = new Array;
	        	//var columnSize = new Array;
	            $('option',select).each(function() {
	                if (this.selected) {
	                    self.jqGrid("showCol", colModel[this.value].name);
	                    
	                    columnName.push(colNames[this.value]);
                    	columnCode.push(colModel[this.value].name); 
                    	columnType.push(colModel[this.value].model);
                    	columnUrl.push(colModel[this.value].url);
                    	//columnSize+=colModel[this.value].index+",";
	                	//alert('this:'+colModel[this.value].name);
	                	//alert('self:'+self);
	                } else {
	                    self.jqGrid("hideCol", colModel[this.value].name);
	                }
	            });
	            
	            var perm = [];
				//fixedCols.slice(0);
	            $('option:selected',select).each(function() { perm.push(parseInt(this.value,10)); });
	            $.each(perm, function() { delete colMap[colModel[parseInt(this,10)].name]; });
	            $.each(colMap, function() {
					var ti = parseInt(this,10);
					perm = insert(perm,ti,ti);
				});
	            if (opts.done) {
	                opts.done.call(self, perm);
	            }
	            
	            $("#"+searchTableId).html(""); 
	            if(!(columnCode == undefined || columnCode == null || columnCode == "" || columnCode.length < 1)){
	            	initInnerHtml += '<tr>';
	            	for(var i=0;i<columnCode.length;i++){
	            		initInnerHtml += '<td width="10%" align="right">';
	            		initInnerHtml += 	'<label>'+columnName[i]+':</label>';
	            		initInnerHtml += '</td>';
	            		
	            		if(columnType[i] == 'text'){
	            			initInnerHtml += '<td width="10%">';
	            			initInnerHtml += 	'<input type="text" name="'+columnCode[i]+'" id="'+columnCode[i]+'" size="25" maxlength="100" />';
	            			initInnerHtml += '</td>';
	            		}else if(columnType[i] == 'check'){
	            			initInnerHtml += '<td width="10%">';
	            			initInnerHtml += 	'<input type="checkbox" name="'+columnCode[i]+'" id="'+columnCode[i]+'" size="25" maxlength="100" value="0"/>';
	            			initInnerHtml += '</td>';
	            		}else if(columnType[i] == 'select'){
	            			initInnerHtml += '<td width="10%">';
	            			initInnerHtml += 	'<select id="'+columnCode[i]+'" name="'+columnCode[i]+'" class="width_c" style="width: 146px;" selectUrl='+columnUrl[i]+'>';
	            			initInnerHtml += 	'</select>';
	            			initInnerHtml += '</td>';
	            		}else if(columnType[i] == 'date'){
	            			initInnerHtml += '<td width="10%">';
	            			initInnerHtml += 	'<input class="centerBaseOutDate" type="text" id="'+columnCode[i]+'ST" name="'+columnCode[i]+'ST"/>-';
	            			initInnerHtml += 	'<input class="centerBaseOutDate" type="text" id="'+columnCode[i]+'ET" name="'+columnCode[i]+'ET"/>';
	            			initInnerHtml += '</td>';
	            		}else if(columnType[i] == 'multiSelect'){
	            			initInnerHtml += '<td width="10%">';
	            			initInnerHtml += 	'<input type="text" name="'+columnCode[i]+'" id="'+columnCode[i]+'" size="25" maxlength="100"/>';
	            			initInnerHtml += 	'<a href="#" class="customizeConditionA" aName="'+columnCode[i]+'" id="centerBaseOutOpStationButton'+columnCode[i]+'" selectUrl="'+columnUrl[i]+'"><img src="/common/images/layout/add.png"/></a>';
	            			initInnerHtml += '</td>';
	            		}else{
	            			initInnerHtml += '<td width="10%">';
	            			initInnerHtml += 	'<input type="text" name="'+columnCode[i]+'" id="'+columnCode[i]+'" size="25" maxlength="100" />';
	            			initInnerHtml += '</td>';
	            		}
	            		if(i % 3 == 2){
	            			initInnerHtml += '<tr>';
	            		}
	            	}
	            }
	            $("#"+searchTableId).append(initInnerHtml);
	            
	            /**设置mutiSelect的弹出DIV**/
	            $("a.customizeConditionA").each(function(){
	            	$(this).click(function() {
	            		getStation($('#'+mutiselectPopCoverCobject), $(this).attr("aName"), false, $(this).attr("selectUrl"));
	            	});
	            });
	            
	            /**动态加载自定义查询面板中的select控件**/
	            $("select").each(function(){
	            	var selectCmp = $(this); 
	            	var url = $(this).attr("selectUrl");
	            	$.ajax({
	            		type:"POST",
	            		dataType:"json",
	            		url:url,
	            		data:{
	            		
	            		},
	            		success:function(data){
	            			selectCmp.empty();
	            			var selectInnerHtml = "";
	            			selectInnerHtml += '<option value="">--请选择--</option>';
	            			if(data != null && data != "" && data.success != null && data.success != "" && data.success != undefined){
	            				var result = data.success;
	    						for(var i=0;i<result.length;i++){
	    							selectInnerHtml += '<option value="'+result[i].key+'">'+result[i].value+'</option>';
	    						} 
	    						selectCmp.append(selectInnerHtml);
	            			}
	            		}
	            	});
	            });
	            
	            /**设置日期控件的JS**/
	            $("input.centerBaseOutDate").datepicker({
	        		dateFormat: 'yy-mm-dd' 
	           	});
	        },
	        /* Function to cleanup the dialog, and select. Also calls the
	           done function with no permutation (to indicate that the
	           columnChooser was aborted */
	        "cleanup" : function(calldone) {
	            call(opts.dlog, selector, 'destroy');
	            call(opts.msel, select, 'destroy');
	            selector.remove();
	            if (calldone && opts.done) {
	                opts.done.call(self);
	            }
	        },
			"msel_opts" : {}
	    }, $.jgrid.col, opts || {});
		if($.ui) {
			if ($.ui.multiselect ) {
				if(opts.msel == "multiselect") {
					if(!$.jgrid._multiselect) {
						// should be in language file
						alert("Multiselect plugin loaded after jqGrid. Please load the plugin before the jqGrid!");
						return;
					}
					opts.msel_opts = $.extend($.ui.multiselect.defaults,opts.msel_opts);
				}
			}
		}
	    if (opts.caption) {
	        //selector.attr("title", opts.caption);
	        selector.attr("title", "选择自定义条件");
	    }
	    if (opts.classname) {
	        selector.addClass(opts.classname);
	        select.addClass(opts.classname);
	    }
	    if (opts.width) {
	        $(">div",selector).css({"width": opts.width,"margin":"0 auto"});
	        select.css("width", opts.width);
	    }
	    if (opts.height) {
	        $(">div",selector).css("height", opts.height);
	        select.css("height", opts.height - 10);
	    }
		var groupdata = [
			                {id:"1",sid:"1",userName:"李we",gender:"男",email:"fef@163.com",QQ:"33334444",mobilePhone:"13223423424",birthday:"1985-10-01",level:"1"},
			                {id:"2",sid:"1",userName:"李四",gender:"女",email:"faf@gmail.com",QQ:"222222222",mobilePhone:"13223423",birthday:"1986-07-01",level:"1"},
			                {id:"3",sid:"1",userName:"王五",gender:"男",email:"fae@163.com",QQ:"99999999",mobilePhone:"1322342342",birthday:"1985-10-01",level:"2"},
			                {id:"4",sid:"1",userName:"马六",gender:"女",email:"aaaa@gmail.com",QQ:"23333333",mobilePhone:"132234662",birthday:"1987-05-01",level:"2"},
			                {id:"5",sid:"1",userName:"赵钱",gender:"男",email:"4fja@gmail.com",QQ:"22222222",mobilePhone:"1343434662",birthday:"1982-10-01",level:"3"},
			                {id:"6",sid:"1",userName:"小毛",gender:"男",email:"ahfi@yahoo.com",QQ:"4333333",mobilePhone:"1328884662",birthday:"1987-12-01",level:"3"},
			                {id:"7",sid:"1",userName:"小李",gender:"女",email:"note@sina.com",QQ:"21122323",mobilePhone:"13220046620",birthday:"1985-10-01",level:"4"},
			                {id:"8",sid:"1",userName:"小三",gender:"男",email:"oefh@sohu.com",QQ:"242424366",mobilePhone:"1327734662",birthday:"1988-12-01",level:"4"},
			                {id:"9",sid:"1",userName:"孙先",gender:"男",email:"76454533@qq.com",QQ:"76454533",mobilePhone:"132290062",birthday:"1989-11-21",level:"5"}
				                ];
	 var params = { width:1680, height:1050,eight:1050 };
	    var str = jQuery.param(params); 
	    $("#results").text(str);
	    // var colModel = self.jqGrid("getGridParam", "colModel");
	    var colModel = self.jqGrid("getGridParam", "colModel");
	    var colNames = self.jqGrid("getGridParam", "colNames");
	    var colMap = {}, fixedCols = [];
	
	    select.empty();
	    $.each(colModel, function(i) {
	        colMap[this.name] = i;
	        if (this.hidedlg) {
	            if (!this.hidden) {
	                fixedCols.push(i);
	            }
	            return;
	        }
	        select.append("<option value='"+i+"' "+
	                (this.hidden?"":"selected='selected'")+">"+jQuery.jgrid.stripHtml(colNames[i])+"</option>");
	        //(this.hidden?"":"selected='selected'")+">"+"chifanfan"+"</option>");
	    });
	    function call(fn, obj) {
	        if (!fn) { return; }
	        if (typeof fn == 'string') {
	            if ($.fn[fn]) {
	                $.fn[fn].apply(obj, $.makeArray(arguments).slice(2));
	            }
	        } else if ($.isFunction(fn)) {
	            fn.apply(obj, $.makeArray(arguments).slice(2));
	        }
	    }
	
	    var dopts = $.isFunction(opts.dlog_opts) ? opts.dlog_opts.call(self, opts) : opts.dlog_opts;
	    call(opts.dlog, selector, dopts);
	    var mopts = $.isFunction(opts.msel_opts) ? opts.msel_opts.call(self, opts) : opts.msel_opts;
	    call(opts.msel, select, mopts);
	},
	occRemapColumns:function(jq , functionName){
		$.ajax({
			type:"POST",
			dataType: "json",
			url:"/orm/getSavedCustomizeConditionColumns.action",
			data: {
				functionName: functionName
			},
			success:function(result){
				try {
					var defaultColModel = jq.jqGrid("getGridParam" , "colModel");
					
					for(var i = 0; i < defaultColModel.length; ++i) {
						jq.jqGrid("hideCol", defaultColModel[i].name);
					}
					if (result != null ) {
						// parse customize data
						var cols = result.customizeConditionList;
						var perm = new Array();
						
						for(var i = 0; i < cols.length; ++i) {
							jq.jqGrid("showCol", cols[i].conditionCode);
						}
					}
				} catch(e) {alert(e);}
				
			}
		});
	}
});
})(jQuery);